<template>
  <div>
    <a-modal
      title-align="start"
      modal-class="transaction-dialog"
      v-model:visible="dialogVisible"
      :closable="false"
      :footer="false"
    >
      <template #title="{ close, titleId, titleClass }">
        <div class="my-header">
          <div :id="titleId" :class="titleClass" v-if="type == 1">
            <h4 style="font-weight: bold">已交付稿件: {{ DownNum }}篇</h4>
            <span style="font-size: 12px; color: #7b7c80">您可以在此查看(或下载)已交付的最新版稿件.</span>
          </div>
          <div :id="titleId" :class="titleClass" v-if="type == 2">
            <h4 style="font-weight: bold">待下载稿件：{{ DownNum }}篇</h4>
            <span style="font-size: 12px; color: #cc5b10">60天后(自确认接收时刻起), 您的稿件将从平台服务器上移除.</span>
          </div>
          <!-- <el-button type="danger" @click="close">下载</el-button> -->
          <div v-if="type == 2 && DownNum > 0" @click="handleDownLoadAll" class="downLoad-commit-button"></div>
          <div v-if="type == 2 && DownNum == 0" class="downLoad-commit-button-forbidden"></div>
        </div>
      </template>
      <div style="width: 100%; height: 0px; border: 1px solid #c6c7cc"></div>
      <div class="my-content">
        <div class="contentgaojian" v-for="(item, index) in props.taskList" :key="index">
          <div style="display: flex; align-items: center; margin-left: 16px; padding-top: 24px">
            <div>
              <div style="font-size: 12px; font-weight: bold; color: #adaeb3">任务ID</div>
              <div style="font-family: Komu A, Komu A; color: #47484d; font-size: 17px; font-weight: bold">
                {{ item.taskId }}
              </div>
            </div>
            <div style="width: 0px; height: 12px; border: 1px solid #000000; opacity: 0.2; margin: 0 25px"></div>
            <div>
              <div style="font-size: 12px; font-weight: bold; color: #adaeb3">收稿时间</div>
              <div style="font-family: Komu A, Komu A; color: #47484d; font-size: 17px; font-weight: bold">
                {{ item.endTime && format(item.endTime, 'yy.MM.dd') }}
              </div>
            </div>
            <div style="width: 0px; height: 12px; border: 1px solid #000000; opacity: 0.2; margin: 0 25px"></div>
            <div>
              <div style="font-size: 12px; font-weight: bold; color: #adaeb3">稿件</div>
              <div style="font-family: Komu A, Komu A; color: #47484d; font-size: 17px; font-weight: bold">
                {{ item.manuscripts_num }}
                <span style="color: #abaeb3; font-size: 14px">篇</span>
              </div>
            </div>
          </div>
          <div style="display: flex; align-items: center; margin-left: 16px; padding-top: 20px; padding-bottom: 24px">
            <div class="manuscript-box" @click="handleDownload(item.taskId, item.keyword)">
              <!-- <img
                src="@/assets/images/mine/icon／manuscript／black@2x.png"
                style="width: 16px; height: 16px; margin: 0 10px"
              /> -->
              <div class="icon-manuscript"></div>
              <div class="manuscript-name" style="flex: 1; width: 0">
                {{ (item.keyword || '').slice(0, 20) }}-{{ item.endTime }}
              </div>
              <div class="manuscript-name" style="width: 130px; text-align: right">
                等共计{{ item.manuscripts_num }}个稿件
              </div>
            </div>
            <div>
              <div class="download-single" @click="handleDownload(item.taskId, item.keyword)"></div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { defineProps } from 'vue'
import { format, add, startOfWeek, subDays } from 'date-fns'
import { queryFilieList as updateTask } from '@/apis'
import { Message } from '@arco-design/web-vue'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import htmlDocx from 'html-docx-js/dist/html-docx'
import axios from 'axios'

const props = defineProps({
  type: {
    type: Number // 声明 message prop，类型为 String
  },
  taskList: {
    type: Array,
    default: []
  }
})
const dialogVisible = ref(false)
const emit = defineEmits(['refresh'])
const DownNum = computed(() => {
  return (
    props.taskList.reduce((prev, dd) => {
      return prev + dd.manuscripts_num
    }, 0) || 0
  )
})
const handleDownLoadAll = () => {
  props.taskList.forEach((item) => {
    handleDownload(item.taskId, item.keyword)
  })
}
const handleDownload = (taskId, keyword) => {
  updateTask({
    switch: 4,
    keyword_id: taskId
  }).then(async (res) => {
    let resData = JSON.parse(res || '{}')
    if (resData.code === 200) {
      let file_Arr = JSON.parse(resData.result || [])
      if (file_Arr.length <= 10) {
        file_Arr.forEach((file) => {
          if (file.url) {
            downloadFile(file)
          }
        })
      } else {
        //大于10个打包下载
        const zip = new JSZip()
        try {
          // 使用 Promise.all 等待所有文件的 Blob 下载完成
          const filePromises = file_Arr.map(async (file) => {
            const blob = await getBlob(file.url)
            const fileName = file.name.endsWith('.docx') ? file.name : `${file.name}.docx`
            const file2 = new File([blob], fileName, { type: blob.type })
            return { name: fileName, file: file2 }
          })

          // 等待所有文件处理完成
          const files = await Promise.all(filePromises)

          // 将所有文件添加到 zip 中
          files.forEach(({ name, file }) => {
            zip.file(name, file)
          })

          // 生成 ZIP 文件
          const content = await zip.generateAsync({ type: 'blob' })
          let zipName = keyword || 'files'
          saveAs(content, `${zipName}.zip`)
        } catch (error) {
          console.error('生成 ZIP 文件失败', error)
        }
      }
    } else {
      Message.error(resData.message)
    }
  })
  setTimeout(() => {
    emit('refresh')
  }, 1000)
}
function convertStyleToWidth(htmlString, containerWidth) {
  // 定义正则表达式以匹配样式中的百分比宽度
  const regex = /style\s*=\s*"[^"]*width\s*:\s*(\d+)%[^"]*"/gi

  // 替换函数
  return htmlString.replace(regex, (match, percentage) => {
    // 计算宽度
    const width = (containerWidth * parseFloat(percentage)) / 100
    // 返回新的宽度属性
    return `width="${width}"`
  })
}
function getBlob(url) {
  return new Promise(async (resolve, reject) => {
    let result = await axios.get(url)
    let curHmtl = result.data || ''
    try {
      // 将HTML内容转换为Word文档
      // var converted = htmlDocx.asBlob(html)
      const updatedHtml = curHmtl.replace(
        /style="width:\s*(\d+\.?\d*)px;\s*height:\s*(\d+\.?\d*)px;"/g,
        (match, width, height) => {
          return `width="${width}" height="${height}"`
        }
      )
      // const newUrl = `<div style="width: 1200px;">${updatedHtml}</div>`
      const updatedHtml2 = convertStyleToWidth(updatedHtml, 1200)
      // 将HTML内容转换为Word文档
      var converted = htmlDocx.asBlob(updatedHtml2)
      resolve(converted)
    } catch (err) {
      reject('word转换失败')
    }
    // const XML = new XMLHttpRequest();
    // XML.open('GET', url, true);
    // // XML.responseType = 'blob';
    // XML.onload = () => {
    // 	if (XML.status === 200) {
    //     // 返回的是html需要转为docx
    // 		// resolve(XML.response);
    //     console.log(XML.response);

    //     debugger
    // 	}
    // };
    // XML.send();
  })
}
const downloadFile = (file) => {
  //下载文件
  function saveAs(blob, filename) {
    const elelink = document.createElement('a')
    elelink.style.display = 'none'
    elelink.download = filename
    elelink.href = window.URL.createObjectURL(blob)
    document.body.appendChild(elelink)
    elelink.click()
    document.body.removeChild(elelink)
  }
  // 调用以上方法进行下载
  getBlob(file.url).then((blob) => {
    saveAs(blob, file.name)
  })
}
const show = () => {
  dialogVisible.value = true
}
defineExpose({
  show
})
</script>

<style scoped lang="scss">
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 16px;
}
.my-content {
  display: inline;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.contentgaojian {
  width: 99.8%;
  background: #fafafa;
  border-radius: 8px;
  margin: 16px 0;
}
</style>
<style lang="scss">
.transaction-dialog {
  padding: 24px;
  border-radius: 12px;
  width: 660px;
  .arco-modal-header {
    text-align: left;
    border: none;
  }
  .downLoad-commit-button {
    width: 186px;
    height: 52px;
    background-size: 100% 100%;
    cursor: pointer;
    background-image: url('@/assets/images/mine/button／downloadAll／normal@2x.png');
    &:hover {
      background-image: url('@/assets/images/mine/button／downloadAll／hover@2x.png');
    }
  }
  .downLoad-commit-button-forbidden {
    width: 186px;
    height: 52px;
    background-size: 100% 100%;
    background-image: url('@/assets/images/mine/button／downloadAll／forbid@2x.png');
  }
  .download-single {
    margin-left: 12px;
    width: 42px;
    height: 42px;
    background-size: 100% 100%;
    cursor: pointer;
    background-image: url('@/assets/images/mine/button／common／download／normal@2x.png');
    &:hover {
      background-image: url('@/assets/images/mine/button／common／download／hover@2x.png');
    }
  }
  .manuscript-box {
    width: 521px;
    height: 42px;
    background: #e1e3e6;
    border-radius: 8px;
    line-height: 42px;
    display: flex;
    align-items: center;
    padding: 0 14px;
    box-sizing: border-box;
    .icon-manuscript {
      background: url('@/assets/images/mine/icon／manuscript／black@2x.png');
      background-size: cover;
      width: 16px;
      height: 16px;
      margin-right: 12px;
    }
    .manuscript-name {
      font-weight: bold;
      font-size: 14px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
    &:hover {
      background: #4560e6;
      color: #e9e9eb;
      .manuscript-name {
        font-weight: bold;
        font-size: 14px;
      }
      .icon-manuscript {
        background: url('@/assets/images/mine/icon／manuscript／white@2x.png');
        background-size: cover;
      }
    }
  }
}
</style>
